import axios from 'axios';
import router from '@/router';
import {
  Message
} from 'element-ui';

//http request 拦截器
axios.interceptors.request.use(
  config => {
    config.timeout = 10000;
    config.baseURL = 'http://ynk_api.frp.iyuce.com';
    let token = window.localStorage.token;
    config.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
    config.headers.post['Content-Type'] = 'application/json';
    if (token) {
      config.headers = {
        'Authorization': 'Bearer ' + token
      }
    }
    return config
  },
  error => {
    return Promise.reject(error);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.code == 401) {
      Message.error(response.message);
      router.push({
        path: '/login'
      });
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
        params: params
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err)
      })
  })
}
